<template>
	<view class="container" :style="addressShow ? 'overflow: hidden;height:90vh;' : ''">
		<!-- 地址提示 -->
		<view class="address-tip">
			<view style="width: 100rpx">
				<u-icon name="map" size="30"></u-icon>
			</view>

			<view v-if="!isChmod">
				<view @click="setAddress()" style="display: flex; justify-content: space-between; align-items: center">
					<view :addressShow="addressShow" v-if="addData.id">
						<view>
							<text class="tip-text">姓名:{{ addData.name }},手机号:{{ addData.phone }}</text>
							<view>
								收货地址:{{ addData.provinceName + addData.cityName + addData.districtName + addData.addressDetail }}
							</view>
						</view>
					</view>

					<view :addressShow="addressShow" v-else>
						<view @click="setAddress(addData.id)"
							style="display: flex; justify-content: space-between; align-items: center">
							<text class="tip-text">暂无收货地址</text>
						</view>
						<text class="tip-desc">（请详细填写本人收货地址，如xx小区x栋xx）</text>
					</view>
					<u-icon name="arrow-right"></u-icon>
				</view>
			</view>
			<view v-else>
				<view class="tip-text" style="display: flex; align-items: center">待自提-门店：<view style="max-width: 62%;">
						{{storeClass}}
					</view>
				</view>
			</view>
		</view>

		<!-- 商品信息 -->
		<view class="orderInfo">
			<image class="order-image" :src="path + dataClass.mainImage" mode="aspectFill"></image>
			<view class="info">
				<view class="infoname">
					<view class="tag">品牌</view>
					<view class="name">{{ dataClass.description || '保密中' }}</view>
				</view>
				<view class="Specifications">规格：{{ forRef.sku.sku || '' }}</view>
				<view class="Specifications">数量：{{ forRef.num }}</view>
				<view class="price">￥{{ forRef.numberSum }}</view>
			</view>
		</view>

		<!-- 租赁参数 -->
		<view class="rental-info">
			<view class="item">
				<text class="label">租期</text>
				<text class="value">{{ forRef.tenancy }}天</text>
			</view>
			<view class="item">
				<text class="label">日租价</text>
				<text class="value">￥{{ forRef.dataSum }}/天</text>
			</view>
			<view class="item">
				<text class="label">租金付款方式</text>
				<text class="value">{{ textRef }}</text>
			</view>
		</view>

		<!-- 底部操作 -->
		<view class="footer">
			<view class="checkbox">
				<u-checkbox-group placement="column" @change="checkboxChange">
					<u-checkbox shape="square"></u-checkbox>
				</u-checkbox-group>

				<text class="agree-text">
					我已阅读并同意签署:
					<view style="color: #1677ff" @click="urlTab()">《重要提示》《未成年声明》《用户租赁协议》</view>
				</text>
			</view>
			<view class="total-button">
				<view class="total">租金：￥{{ forRef.numberSum }}</view>
				<button class="submit-btn" @click="canOrder()">确认下单</button>
			</view>
		</view>

		<!-- </u-popup> -->
		<u-popup mode="bottom" :show="addressShow" :round="15">
			<view class="addressContent">
				<!-- 填写地址 -->
				<addRess ref="childComponent" @index-class="address" @closePopup="closePopup"
					@popuoSubmit="popuoSubmit"></addRess>
				<!-- 填写地址 -->
			</view>
		</u-popup>
	</view>
</template>

<script>
	import addRess from '../../components/address/index.vue';
	import api from '@/api/index.js';
	import main from '@/api/main.js';
	import address from '@/api/address.js';
	import {
		idCardValidate
	} from '@/utils/validate.js';
	import {
		baseUrl
	} from '../../config.js';
	import order from '../../api/order';
	export default {
		components: {
			addRess
		},
		data() {
			return {
				fileList1: [],
				addressShow: false,
				checked: false,
				textRef: '支付宝',
				indexClass: {}, //地址
				forRef: {},
				dataClass: {},

				path: api.getPath(),
				baseUrl: api.getPathApi(),
				addData: {},
				isCard: 0,
				//是否自提
				isChmod: false,
				storeClass: ""
			};
		},
		onLoad(e) {
			if (e.forRef) {
				const forRefInfo = JSON.parse(decodeURIComponent(e.forRef));
				this.getIdClass(forRefInfo.id);
				this.forRef = forRefInfo;
				this.isChmod = forRefInfo.chmod == '自提' ? true : false;
			}
			this.getOrderList();
		},
		onShow() {
			if (this.addressShow) {
				this.addressShow = false;
				setTimeout(() => {
					this.addressShow = true;
				}, 500);
			}
			this.getStore()
		},

		mounted() {
			//获取默认地址
			this.getDefaultAddress();
		},
		methods: {
			getStore() {
				order.systemInfoList({
					title: "自提门店"
				}).then((res) => {
					this.storeClass = res.rows[0].content.replace(/<[^>]+>/g, '').replace(/&nbsp;/g, ' ');
				})
			},
			urlTab() {
				uni.navigateTo({
					url: '/subPages/mine/agreement'
				});
			},
			closePopup(e) {
				this.addressShow = false;
			},
			popuoSubmit(e) {
				this.addressShow = false;
				setTimeout(() => {
					this.getDefaultAddress();
				}, 1000);
			},
			getDefaultAddress() {
				address
					.addressList()
					.then((res) => {
						if (res.code == 200) {
							this.addressList = res.rows;
							this.addData = this.addressList[0];
						}
					})
					.catch((erro) => {
						console.log('error');
					});
			},

			getIdClass(id) {
				main.getIdClass(id)
					.then((data) => {
						this.dataClass = data.data;
					})
					.catch((erro) => {
						console.log('没找到商品', erro);
					});
			},

			address(row) {
				this.indexClass = row;
			},

			checkboxChange() {
				this.checked = !this.checked;
			},

			handleUpload(type) {},
			setAddress() {
				this.addressShow = true;
			},
			addressClose() {
				this.addressShow = false;
			},
			addressConfirm() {
				this.addressShow = false;
			},
			//创建订单
			async canOrder() {
				if (!this.checked) {
					uni.showToast({
						title: '请勾选协议后在继续',
						icon: 'none', // 可选 success/loading/none
						duration: 2000 // 持续时间，单位ms
					});
					return;
				}
				if (!this.addData && !this.isChmod) {
					uni.showToast({
						title: '请选择地址',
						icon: 'none', // 可选 success/loading/none
						duration: 2000 // 持续时间，单位ms
					});
					this.setAddress();
					return;
				}

				const modalRes = await new Promise((resolve, reject) => {
					wx.showModal({
						title: '免押',
						content: `本单租金￥${this.forRef.numberSum}，押金￥${this.forRef.sku.cashPledge}，应支付￥${(this.forRef.numberSum + this.forRef.sku.cashPledge).toFixed(2)}，免押金额以信用免押额度为准，免押后将同步支付租金及剩余押金`,
						success: resolve,
						fail: reject
					});
				});

				// 2. 仅当用户点击取消时触发
				if (!modalRes.confirm) {
					return
				}

				main.setOrder({
						productSkuId: this.forRef.sku.leaseRentalRules[0].productSkuId, //商品ID
						quantity: this.forRef.num, //数量
						useraddrId: this.isChmod ? '' : this.addData.id, //用户地址id
						rentalPeriod: this.forRef.tenancy, //天数
						productId: this.dataClass.id,
						deliveryMethod: this.isChmod ? 2 : 1, //配送方式
						rentalDays: 1,
						rentalDaysUnit: 30,
						cashPledge: this.forRef.sku.cashPledge,
						address: this.storeClass,
						productName: this.forRef.productName,
					})
					.then((data) => {
						if (data.code == 200) {
							uni.showToast({
								title: '下单成功',
								icon: 'success', // 可选 success/loading/none
								duration: 2000 // 持续时间，单位ms
							});
							const orderClass = JSON.parse(data.msg)
							console.log(orderClass)

							order.getFreeDetain(orderClass.id).then((data) => {
								my.tradePay({
									orderStr: data.orderStr,
									success: (res) => {
										if (res.resultCode == 9000) {
											// this.setPay(orderClass.orderNumber);
											uni.reLaunch({
												url: '/subPages/mine/allOrder'
											});
										}
									},
									fail: (error) => {
										console.error('调用 my.tradePay 失败: ', JSON.stringify(
											error));
									}
								});
							})
						}
					})
					.catch((erro) => {
						console.log(erro, "下单失败");
					});
			},
			//main.setPay(id)
			setPay(id) {
				console.log(id)
				main.setPay(id)
					.then((data) => {
						// let outTradeNo = data.outTradeNo;
						let tradeNo = data.tradeNo;

						// 调用统一收单交易创建接口（alipay.trade.create），获得返回字段支付宝交易号 trade_no
						my.tradePay({
							tradeNO: tradeNo,
							success: (res) => {
								if (res.resultCode == 9000) {
									uni.reLaunch({
										url: '/subPages/mine/allOrder'
									});
								}
							},
							fail: (error) => {
								console.error('调用 my.tradePay 失败: ', JSON.stringify(error));
							}
						});

						// my.alert({
						// 	content: JSON.stringify('qqqqqqqqqqqqqqqq' + data.orderStr)
						// });
						// my.tradePay({
						// 	orderStr: data.orderStr, // 完整的支付参数拼接成的字符串，从 alipay.fund.auth.order.app.freeze 接口获取
						// 	success: (res) => {
						// 		my.alert({
						// 			content: JSON.stringify(res)
						// 		});
						// 	},
						// 	fail: (res) => {
						// 		my.alert({
						// 			content: JSON.stringify(res)
						// 		});
						// 	}
						// });
					})
					.catch((erro) => {
						console.log(erro);
					});
			},

			getOrderList() {
				main.getOrderList({
						pageNo: 1,
						pageSize: 30
					})
					.then((data) => {})
					.catch((erro) => {
						console.log(erro);
					});
			}
		}
	};
</script>

<style lang="scss" scoped>
	.error-text {
		color: #ff4545;
		font-size: 24rpx;
		margin-top: 10rpx;
	}

	.order-image {
		width: 185rpx;
		height: 166rpx;
		margin-right: 15rpx;
		border-radius: 10rpx;
	}

	.container {
		padding-bottom: 20rpx;
		background-color: #eee;
		height: calc(100vh + 200rpx);

		.orderInfo {
			box-sizing: border-box;
			display: flex;
			background-color: #fff;
			margin: 30rpx;
			padding: 25rpx;
			border-radius: 10rpx;

			.info {
				display: flex;
				flex-direction: column;
				justify-content: space-around;
			}

			.infoname {
				display: flex;
				align-items: center;

				.tag {
					width: 64rpx;
					height: 36rpx;
					line-height: 36rpx;
					text-align: center;
					color: #1677ff;
					background-color: #deecff;
					border-radius: 25px;
					font-size: 20rpx;
					margin-right: 8rpx;
				}

				.name {
					font-size: 28rpx;
				}

				.mode {
					width: 64rpx;
					height: 36rpx;
					line-height: 36rpx;
					text-align: center;
					color: #ff8662;
					border: 1px solid #ff8662;
					border-radius: 3px;
					font-size: 20rpx;
					margin-left: 15rpx;
				}
			}

			.Specifications {
				color: #777;
				font-size: 24rpx;
			}

			.price {
				font-size: 30x;
				color: red;
				font-weight: 600;
			}
		}

		.address-tip {
			margin-top: 30rpx;
			padding: 30rpx;
			background: #fff;
			border-radius: 10rpx;
			display: flex;
			align-items: center;
			margin: 20rpx;

			.tip-text {
				margin-right: 20rpx;
				font-size: 32rpx;
				color: black;
			}

			.tip-desc {
				display: block;
				margin-top: 15rpx;
				font-size: 26rpx;
				color: red;
			}
		}
	}

	.rental-info {
		background: #fff;
		padding: 30rpx;
		margin: 20rpx;
		border-radius: 10rpx;

		.item {
			display: flex;
			justify-content: space-between;
			padding: 20rpx 0;
			border-bottom: 1rpx solid #eee;
		}
	}


	.footer {
		padding: 30rpx;
		padding-bottom: calc(80rpx + env(safe-area-inset-bottom));
		background: #fff;
		position: fixed;
		bottom: 0;
		width: 100%;
		height: 150rpx;
		box-shadow: 0 -2rpx 6rpx rgba(0, 0, 0, 0.1);

		.checkbox {
			display: flex;
			align-items: center;
			margin-bottom: 20rpx;

			.agree-text {
				max-width: 90vw;
				color: #666;
				margin-left: 20rpx;
			}
		}

		.total-button {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin: 0 50rpx;

			.total {
				font-size: 36rpx;
				color: #ff3b30;
				font-weight: bold;
				text-align: right;
				margin-bottom: 30rpx;
			}

			.submit-btn {
				width: 300rpx;
				height: 80rpx;
				line-height: 80rpx;
				font-size: 34rpx;
				background-color: #1677ff;
				border-radius: 50rpx;
				color: #fff;
			}
		}
	}
</style>